//消息管理中心

using System;
using System.Collections.Generic;

public class MessageCenter
{
    //委托：消息传递
    public delegate void OnMessageHandler(object userData);
    public static Dictionary<string, LinkedList<OnMessageHandler>> _dicMessage = new Dictionary<string, LinkedList<OnMessageHandler>>();

    /// <summary>
    /// 观察者监听事件
    /// </summary>
    public static void AddMsgListener(string key, OnMessageHandler handler)
    {
        LinkedList<OnMessageHandler> lstHandler = null;
        _dicMessage.TryGetValue(key, out lstHandler);
        if (lstHandler == null)
        {
            lstHandler = new LinkedList<OnMessageHandler>();
            _dicMessage[key] = lstHandler;
        }
        lstHandler.AddLast(handler);
    }

    /// <summary>
    /// 观察者移除监听事件
    /// </summary>
    public static void RemoveMsgListener(string key, OnMessageHandler handler)
    {
        LinkedList<OnMessageHandler> lstHandler = null;
        _dicMessage.TryGetValue(key, out lstHandler);
        if (lstHandler != null) lstHandler.Remove(handler);
    }
    public void RemoveMsgListenerAll(string key)
    {
        LinkedList<OnMessageHandler> lstHandler = null;
        _dicMessage.TryGetValue(key, out lstHandler);
        if (lstHandler != null) lstHandler.Clear();
    }

    /// <summary>
    /// 派发
    /// </summary>
    public static void Dispatch(string key, object userData)
    {
        LinkedList<OnMessageHandler> lstHandler = null;
        _dicMessage.TryGetValue(key, out lstHandler);

        if (lstHandler != null && lstHandler.Count > 0)
        {
            for (LinkedListNode<OnMessageHandler> curr = lstHandler.First; curr != null; curr = curr.Next)
            {
                if (curr.Value.Target != null)
                {
                    curr.Value?.Invoke(userData);
                }
            }
        }
    }

    public static void Dispatch(string key)
    {
        Dispatch(key, null);
    }
}